package org.ece.meteo.httpservlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.osgi.framework.BundleContext;

/*
 * BEWARE !!! This servlet is given AS THIS without any guarantee
 * It has some security risks (injection code), you should NEVER
 * 	display arguments without any tests.
 */

public class meteoServlet extends HttpServlet {
		/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final int maxAlertNb = 12;	// This is the rotative log length
	private static String[] alerts;
	
	public meteoServlet(BundleContext bc) {
			alerts = new String[maxAlertNb];	// wanna store last alerts
		    for(int i = 0; i < maxAlertNb; i++) {	// initialize it
		    	alerts[i] = null;
		    }
		}

	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		response.addHeader("Refresh", "8");		// auto refresh the page each 8 seconds
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head><title>OSGi Meteo Servlet</title>");
		//out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"/www/meteo.css\" />");     		
	
		out.println("</head>");
		out.println("<body>");
		out.println("<h2>What is the weather today?</h2>");
		out.println("<p>Please not that only last alerts are going to be displayed bellow</p>");
		printAlert(request, out);
		out.println("</body>");
		out.println("</html>");
		
		}
	
	void printAlert(HttpServletRequest request, PrintWriter out) throws IOException {
	    int i =0;
	    DateFormat df = new SimpleDateFormat("HH:mm:ss");
	    String param = request.getParameter("alert");
	    if(param != null){
	    	// rotate the log... We always want to fill the last line.
		    while((i <= (maxAlertNb-2)) /*&& (alerts[i] != null) */){	
		    	alerts[i] = alerts[i+1];	
		    	i++;
		    }
		    try{
		    	alerts[i] = df.format(System.currentTimeMillis()) + " - " + param.replace("_", " ");	// You should really add other tests (about parameters)	    		    
		    }catch (Exception e) {
				e.printStackTrace();
			}
	    }
		out.println("<pre>");
	    for(i = 0; i < alerts.length; i++) {
	    	if(alerts[i] != null)
	    		out.println(alerts[i]);		// Print last alerts
	    }
	    out.println("</pre>");
	  }
}

